/*
 * Copyright 2014 by État de Genève (Switzerland)
 * All rights reserved.
 *
 * Author: ELCA Informatique SA
 */
define(['services/notifier', 'services/formatter', 'i18n', 'services/config'],
    function (notifier, formatter, i18n, config) {
        return {
            init: function (element, valueAccessor, allBindings) {
                var value = valueAccessor();
                var url = allBindings().url || config.api.uploadUrl;
                var isReadonly = !!allBindings().readonly;
                var report = allBindings().validationReport;

                if (!url) {
                    throw new Error('No url for uploader');
                }

                var me = config.browser;
                if(me && me.type && me.type.toUpperCase() === 'MSIE' && me.version <= 9) {
                    $(element).append(
                            '<input type="file" name="file">'
                            + '<span class="form-control op-file-upload"><i class="mi mi-files-12"></i></span>');
                } else {
                    // creates HTML elements inside the uploader binding
                    $(element).append(
                            '<input type="file" class="hidden" name="file">'
                            + '<span class="form-control op-file-upload"><i class="mi mi-files-12"></i></span>'
                            + '<span class="input-group-btn">'
                            + '<button class="btn btn-default">Parcourir</button>'
                            + '</span>');
                }


                if(!isReadonly) {
                    // add events to elements hiding the uploader
                    $('.btn', element).click(function (e) {
                        e.preventDefault();
                        // Warning: the uploader is recreated at each upload by the jquery plugin
                        // be sure to match the new input, and to not have one stored in a closure
                        $('input[type="file"]', element).get(0).click();
                        return false;
                    });

                    $('input[type="file"]', element).fileupload({
                        url: url,
                        dataType: 'json',
                        // default validation do not work in the the plugin, override the add function.
                        add: function (e, data) {
                            var acceptFileTypes = /^application\/pdf$/i;
                            // accept only PDFs
                            if (data.originalFiles[0]['type'] && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
                                notifier.alert(i18n.ts('cms:error.uploadType', 'PDF'));
                            } else {
                                // accept only files < 5MB
                                if (data.originalFiles[0]['size'] && data.originalFiles[0]['size'] > 5 * 1024 * 1024) {
                                    notifier.alert(i18n.ts('cms:error.uploadFileSize', '5Mo'));
                                } else {
                                    data.submit();
                                }
                            }
                        },
                        done: function (e, data) {
                            // json result from API is wrapped in data.result (and ResultWithAlerts also contains a result...)
                            if (data && data.result && data.result.result) {
                                if (ko.isObservable(value)) {
                                    value(data.result.result);
                                }

                                // if there's validation data, update errors
                                if(data.validation && report && ko.isObservable(report)) {
                                    report(data.validation);
                                }
                            } else {
                                notifier.alert(i18n.t('cms:error.uploadError'));
                            }
                        },
                        progress: function(e, data) {
                            // could update an upload bar here if necessary...
                        },
                        fail: function(e, data) {
                            notifier.alert(i18n.t('cms:error.uploadError'));
                        },
                        start: function(e, data) {
                        }
                    });
                } else {
                    $('.btn', element).attr('disabled', 'disabled');
                    $('input[type="file"]', element).attr('class', 'hidden');
                    $(element).addClass('disabled');
                    $('.form-control').addClass('disabled');
                }
            },
            update: function (element, valueAccessor, allBindings) {
                var file = ko.unwrap(valueAccessor());
                var report = allBindings().validationReport;

                if (file && ko.unwrap(file.nomFichier)) {
                    var size = ko.unwrap(file.taille),
                        name = ko.unwrap(file.nomFichier);

                    var icon = 'files-34';

                    $('.op-file-upload', element).html(
                            '<i class="mi mi-' + icon + '"></i> '
                            + '<span>' + size + '</span>&nbsp; '
                            + '<strong>' + (name || '-') + '</strong>'
                    );
                } else {
                    $('.form-control', element).html('');
                }
            }
        };
    });